<template>
  <Form ref="target" :validation-schema="ruler" v-slot="{ errors }">
    <div class="xtx-form">
      <div class="user-info">
        <img :src="avatar" alt="" />
        <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
      </div>
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-phone"></i>
          <Field
            class="input"
            type="text"
            v-model="formData.mobile"
            :class="{ err: errors.mobile }"
            name="mobile"
            placeholder="绑定的手机号"
          />
        </div>
        <div class="error" v-if="errors.mobile">
          <i class="iconfont icon-warning" />{{ errors.mobile }}
        </div>
      </div>
      <div class="xtx-form-item">
        <div class="field">
          <i class="icon iconfont icon-code"></i>
          <Field
            class="input"
            type="text"
            :class="{ err: errors.code }"
            v-model="formData.code"
            name="code"
            placeholder="短信验证码"
          />
          <span class="code" @click="send">{{
            time === 0 ? "发送验证码" : `${time}秒后重发`
          }}</span>
        </div>
        <div class="error" v-if="errors.code">
          <i class="iconfont icon-warning" />{{ errors.code }}
        </div>
      </div>
      <a href="javascript:;" class="submit" @click="submit">立即绑定</a>
    </div>
  </Form>
</template>

<script>
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
// 引入表单校验功能
import { Form, Field } from 'vee-validate'
// 引入表单校验
import validateForm from '@/utils/validate'
// 引入封装倒计时函数
import { useCountDown } from '@/compositions/index'
import Message from '@/components/Message.js'
import { userQQBindCode } from '@/api/user'
import QC from 'qc'
export default {
  name: 'CallbackBind',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const store = useStore()
    const router = useRouter()
    // 定义头像和昵称
    const avatar = ref('')
    const nickname = ref('')
    QC.Login.check() && QC.api('get_user_info').success(res => {
      // 保存头像和昵称
      avatar.value = res.data.figureurl_qq
      nickname.value = res.data.nickname
    })

    // 表单校验，
    // 1.定义数据项
    const formData = reactive({
      mobile: '',
      code: ''
    })
    // 2.定义校验规则
    const ruler = {
      mobile: validateForm.mobile,
      code: validateForm.code
    }

    // 兜底校验
    const target = ref(null)
    const submit = () => {
      // Form 组件提供了一个 validate 函数作为整体表单校验，返回的是一个promise
      target.value.validate().then(async (res) => {
        // console.log('表单校验结果', res)
        if (res) {
          // 做提交动作(校验通过)
          try {
            await store.dispatch('user/userQQBindLogin', { unionId: props.unionId, mobile: formData.mobile, code: formData.code })
            // 同步购物车
            await store.dispatch('cart/mergeLocalCart')
            Message({ type: 'success', text: '绑定成功' })
            router.push('/')
          } catch (err) {
            Message({ type: 'error', text: err.response.data.message })
          }
        }
      })
    }

    // 发送手机验证码
    const { time, start } = useCountDown()
    const send = () => {
      // 使用倒计时函数
      // 发送验证码
      if (!validateForm.mobile(formData.mobile)) {
        Message({ type: 'error', text: '手机号格式不正确' })
        return
      }
      // 发请求获取验证码
      if (time.value !== 0) {
        return
      }
      userQQBindCode(formData.mobile).then(() => {
        start(60)
        Message({ type: 'success', text: '验证码已发送' })
      }).catch(err => {
        console.log(err)
        // Message({ type: 'error', text: err.response.data.message })
      })
    }

    return { avatar, nickname, formData, ruler, target, submit, send, time }
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
